<?php


namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\ArraySort;
use StarCloud\Library\HttpCurl;

class FhNovel
{
    use HttpCurl;
    /* @var $httpClient HttpClient */
    private $httpClient = null;

    public function __construct()
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function getQrCode($path, $type)
    {
        $body = [
            'path' => $path,
            'type' => $type,
        ];
        $header = $this->getHeader();
        $header['Content-Type'] = 'application/x-www-form-urlencoded';
        $response =  $this->httpClient->sendPostRequestUrlEncode("https://androidapi4.yc.ifeng.com/api/CZMGZ/getQRCode?", $body, $header);
        $json = json_decode($response->getBody()->getContents(), true);

        return $json['data']['img'] ?? "";
    }

    public function passphrase($senceId, $bookId)
    {
        $body = [
            'bookId' => $bookId,
            'custom_params' => $senceId,
        ];

        $response =  $this->httpClient->sendGetRequest("https://androidapi4.yc.ifeng.com/api/CZMGZ/CreatePassphrase?" . http_build_query($body), $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        return $json['passphrase'];
    }

    public function getCategory()
    {
        $cacheResult = $this->getCacheCategory();

        if (!empty($cacheResult)) {
            return  $cacheResult;
        }

        $body = [];
        $response =  $this->httpClient->sendGetRequest("https://androidapi4.yc.ifeng.com/api/CZMGZ/GetCategory?" . http_build_query($body), $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);


        $res=[];
        foreach ($json['data'] as $item) {
            $data = $this->getList(1, $item['id']);
            if ($data['totalCount'] == 0) {
                continue;
            }
            $temp = explode("-", $item['name']);
            $res[$temp[0]][] = [
                'count' => $data['totalCount'],
                'id' => $item['id'],
                'name' => $temp[1],
            ];
        }

        foreach ($res as &$resItem) {
            $resItem = array_merge([[
                'id' => 0,
                'name' => "全部",
            ]],  ArraySort::multiSort($resItem, ['id' => SORT_ASC]));
        }
        $this->setCacheCategory($res);
        return $res;
    }

    public function setCacheCategory($res) {

        if (is_array($res)) {
            $res = json_encode($res);
        }

        $this->cacheClass->set("fh_novel:category", $res, 86400 * 10);
    }

    public function getCacheCategory() {
        $result = $this->cacheClass->get("fh_novel:category");
        $result = json_decode($result, true);

        return empty($result) ? [] : $result;
    }



    private function getHeader()
    {
        return [
            'appId' => 'dm',
        ];
    }

    public function queryOrder($page, $startTime, $endTime)
    {
        $body = [
            'page' => $page,
            'startTime' => $startTime,
            'endTime' => $endTime
        ];

        $response =  $this->httpClient->sendPostRequest("https://androidapi4.yc.ifeng.com/api/CZMGZ/GetOrderList?" . http_build_query($body), $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        if (isset($json['totalCount']) && $json['totalCount'] > 0) {
            return $json['data'];
        }

        return [];
    }

    public function getList($page, $categoryId = 0, $name = "")
    {
        $body = [
            'page' => $page
        ];
        if (!empty($name)) {
            $body['name'] = $name;
        }
        if (!empty($categoryId)) {
            $body['categoryId'] = $categoryId;
        }
        $response =  $this->httpClient->sendGetRequest("https://androidapi4.yc.ifeng.com/api/CZMGZ/GetBookList?" . http_build_query($body), $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (empty($json['data']) || ($page - 1) * 200 > $json['totalCount']) {
             return [
                 'data' => [],
                 'totalCount' => $json['totalCount'],
             ];
        }

        return [
            'data' => $json['data'],
            'totalCount' => $json['totalCount'],
            'next' => $page
        ];
    }

    public function getBookInfo($bookId)
    {
        $bookInfo = $this->getCacheBookInfo($bookId);

        if (!empty($bookInfo)) {
            return  $bookInfo;
        }
        $body = [
            'bookId' => intval($bookId)
        ];
        $response =  $this->httpClient->sendGetRequest("https://androidapi4.yc.ifeng.com/api/CZMGZ/GetBookInfo?".http_build_query($body), [], $this->getHeader());
        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            $this->setCacheBookInfo($bookId, $json['data']);
            return $json['data'];
        }

        return [];
    }

    public function getBookCacheKey($bookId)
    {
        return "fenghuangwangxiaoshuo:bookinfo:".$bookId;
    }

    private function setCacheBookInfo($bookId, $bookInfo)
    {
        if (is_array($bookInfo)) {
            $bookInfo = json_encode($bookInfo);
        }

        $this->cacheClass->set($this->getBookCacheKey($bookId), $bookInfo, 86400);
    }

    public function getCacheBookInfo($bookId)
    {
        $bookInfo = $this->cacheClass->get($this->getBookCacheKey($bookId));
        $bookInfo = json_decode($bookInfo, true);

        return empty($bookInfo) ? false : $bookInfo;
    }
}